package lily.phs.entertain;



import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lily.phs.urh.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery.LayoutParams;


public class ImageActivity extends Activity implements 
  AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory   {
	 /** Called when the activity is first created. */
	
		private List<String> ImageList;
		private String []list;
	  private ImageSwitcher mSwitcher;
	  TextView tv_TitleBar;
//	  private GridView toolbarGrid;
	  
	  
	  @Override
	  public void onCreate(Bundle savedInstanceState)
	  {
	    super.onCreate(savedInstanceState);
	    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	    setContentView(R.layout.image);  
	    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title);
		
		tv_TitleBar = (TextView)this.findViewById(R.id.title);
        tv_TitleBar.setText("图片浏览");
	    Button btBack = (Button)this.findViewById(R.id.title_left_btn);
		btBack.setText("后退");
		btBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
		});
		Button btSave = (Button)this.findViewById(R.id.title_right_btn);
		btSave.setVisibility(View.GONE);
		Button btSubmit = (Button)this.findViewById(R.id.title_right_btn2);
		btSubmit.setVisibility(View.GONE);
		
        ImageList=getSD();
        list = ImageList.toArray(new String[ImageList.size()]);
	    
	    /*设定Switcher*/
	    mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
	    mSwitcher.setFactory(this);
	    /*设定载入Switcher的模式*/
	    mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
	            android.R.anim.slide_in_left));
	    /*设定输出Switcher的模式*/
	    mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
	            android.R.anim.slide_out_right));
	    
	    
	    Gallery g = (Gallery) findViewById(R.id.mygallery);
	            
	    /*新增几ImageAdapter并设定给Gallery对象*/
	    g.setAdapter(new ImageAdapter(this,getSD()));
	    
	    g.setOnItemSelectedListener(this);

	    /*设定一个itemclickListener事件*/
	    g.setOnItemClickListener(new OnItemClickListener() 
	    {
	      public void onItemClick(AdapterView<?> parent, 
	                       View v, int position, long id) 
	      { 
	      }
	    });
	    
		
		new myThread(handler).start();
	  }
	  
	  /*设定载丈Switcher的图档*/


	  
	  
	  private List<String> getSD()
	  {
	    /* 设定目前所在路径 */
	    List<String> it=new ArrayList<String>();      
	    File f=new File("/sdcard/");  
	    File[] files=f.listFiles();
	 
	    /* 将所有文件存入ArrayList中 */
	    for(int i=0;i<files.length;i++)
	    {
	      File file=files[i];
	      if(getImageFile(file.getPath()))
	        it.add(file.getPath());
	    }
	    return it;
	  }
	    
	  private boolean getImageFile(String fName)
	  {
	    boolean re;
	    
	    /* 取得扩展名 */
	    String end=fName.substring(fName.lastIndexOf(".")+1,
	                  fName.length()).toLowerCase(); 
	    
	    /* 按扩展名的类型决定MimeType */
	    if(end.equals("jpg")||end.equals("gif")||end.equals("png")
	            ||end.equals("jpeg")||end.equals("bmp"))
	    {
	      re=true;
	    }
	    else
	    {
	      re=false;
	    }
	    return re; 
	  }

	  /*改写BaseAdapter自定义一ImageAdapter class*/
	  public class ImageAdapter extends BaseAdapter 
	  {
	    /*声明变量*/
	    int mGalleryItemBackground;
	    private Context mContext;
	    private List<String> lis;
	    
	    /*ImageAdapter的构造符*/
	    public ImageAdapter(Context c,List<String> li) 
	    {
	      mContext = c;
	      lis=li;
	      /* 使用res/values/attrs.xml中的<declare-styleable>定义
	      * 的Gallery属性.*/
	      TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
	      /*取得Gallery属性的Index id*/
	      mGalleryItemBackground = a.getResourceId(
	          R.styleable.Gallery_android_galleryItemBackground, 0);
	      /*让对象的styleable属性能够反复使用*/ 
	      a.recycle();
	    }
	    
	    /*几定要重写的方法getCount,传回图片数目*/
	    public int getCount() 
	    {
	      return lis.size();
	    }
	    
	    /*一定要重写的方法getItem,传回position*/
	    public Object getItem(int position) 
	    {
	      return position;
	    }
	    
	    /*一定要重写的方法getItemId,传并position*/
	    public long getItemId(int position) 
	    {
	      return position;
	    }
	    
	    /*几定要重写的方法getView,传并几View对象*/
	    public View getView(int position, View convertView, 
	                          ViewGroup parent) 
	    {
	      /*产生ImageView对象*/
	      ImageView i = new ImageView(mContext);
	      /*设定图片给imageView对象*/
	      Bitmap bm = BitmapFactory.decodeFile(lis.
	                            get(position).toString());
	      i.setImageBitmap(bm);
	      /*重新设定图片的宽高*/
	      i.setScaleType(ImageView.ScaleType.FIT_XY);
	      /*重新设定Layout的宽高*/
	      i.setLayoutParams(new Gallery.LayoutParams(136, 88));
	      /*设定Gallery背景图*/
	      i.setBackgroundResource(mGalleryItemBackground);
	      /*传回imageView对象*/
	      return i;
	    }     
	  }

	  
	  
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		  String  photoURL=list[position];
		  Log.i("A",String.valueOf(position));
	      mSwitcher.setImageURI(Uri.parse(photoURL));
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public View makeView() {
	    ImageView i = new ImageView(this);
	    i.setBackgroundColor(0xFF000000);
	    i.setScaleType(ImageView.ScaleType.FIT_CENTER);
	    i.setLayoutParams(new ImageSwitcher.LayoutParams(
	        LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
	    return i;
	} 
	
	public class myThread extends Thread{  
		private Handler handler;
		public myThread(Handler handler){
			this.handler=handler;
		}
		
		public void run(){  
	        try  
	        {   
	        	Looper.getMainLooper();
	        	sleep(1000);
	        	//System.out.println("toolbarGrid.getHeight()="+toolbarGrid.getHeight());
	        	Message msg = handler.obtainMessage(); 
	        	msg.what=1;
	        	handler.sendMessage(msg); 
			}  
		    catch (Exception e)  
		    {  
		        e.printStackTrace();  
		    }  
		}  
	}
		
	private final Handler handler = new Handler(Looper.getMainLooper()) {
    	public void handleMessage(Message msg) {
    		DisplayMetrics metrics=new DisplayMetrics();
    		getWindowManager().getDefaultDisplay().getMetrics(metrics); 
    		int height=(int)metrics.heightPixels-60-40-40;
    		System.out.println("Hight="+height);
    		
    		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mSwitcher.getLayoutParams(); 
    		linearParams.height = height;
    		//mGrid.setLayoutParams(linearParams);
    		mSwitcher.setLayoutParams(linearParams);
    		//let.setLayoutParams(linearParams);
    		
    		//System.out.println("yaofangListView.getHeight()="+mListView.getHeight());
    		//ll.set
    	} 
    };
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			intent.setClass(this, YuleActivity.class);
			startActivity(intent);
			finish();
		}
		return true;
    }
}